import * as React from 'react';
import { useNavigate } from 'react-router-dom';
import { Button, Loading, Mask, Toast } from 'antd-mobile';
import { payQuery, pay } from './alipay';
import './index.module.scss';
const { useEffect } = React;

interface orderStatusProps {
  orderStatus: number;
}
export default function BottomButton(props: orderStatusProps) {
  const { orderStatus } = props;
  const navigate = useNavigate();
  const [text, setText] = React.useState('支付结果查询中');
  const [visible, setVisible] = React.useState(false);
  let timeId: any;
  const handerclick = async (val: number) => {
    if (val === 3 || val === 4) {
      navigate('/');
    } else if (val === 2) {
      const outTradeNo = new Date().getTime();
      payTicket(outTradeNo);
      payQueryApi(outTradeNo);
    }
  };
  function payQueryApi(outTradeNo: number) {
    setVisible(true)
    const timer = setInterval(async () => {
      const res: any = await payQuery({ outTradeNo: outTradeNo });
      console.log(res);
      switch (res.data) {
        case '交易创建，等待买家付款':
          setText('交易创建，等待买家付款');
          break;
        case '交易支付成功':
          setText('交易支付成功');
          clearInterval(timer); 
          setTimeout(() => {
            Toast.show({ icon: 'success', content: '支付成功' });
            navigate('/orderFinish');
          }, 3000);
          break;
      }
    }, 1000);
  }
  function payTicket(outTradeNo: number) {
    pay({
      tradeNo: 1000,
      outTradeNo: outTradeNo,
      totalAmount: 1,
      subject: '开发测试使用',
    });
  }

  useEffect(() => {
    return () => {
      clearTimeout(timeId);
    };
  }, []);

  return (
    <div styleName="bottom-button">
      <Button
        styleName="pay-button"
        fill="none"
        onClick={() => {
          handerclick(orderStatus);
        }}
      >
        {orderStatus == 2
          ? '去支付'
          : orderStatus == 3 || orderStatus == 4
          ? '重新订购'
          : ''}
      </Button>

      <Mask
        visible={visible}
        style={{
          color: 'white',
          display: 'flex',
          justifyContent: 'center',
          alignItems: 'center',
        }}
      >
        <span>{text}...</span>
        <Loading></Loading>
      </Mask>
    </div>
  );
}
